import citycode from '@/assets/citycode.json';
import { SUCCESS_CODE } from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageHeaderWrapper, ProTable } from '@ant-design/pro-components';
// import type { UploadFile } from 'antd';
import { Button, message, Modal, Popover, Select, Tag } from 'antd';
// import modal from 'antd/lib/modal';
import type { SorterResult } from 'antd/lib/table/interface';
import { useRef, useState } from 'react';
import AddParkList from './component/AddParkList';
import ConfigImage from './component/ConfigImage';
import ParkDetail from './component/ParkDetail';
import UndataParkList from './component/UndateParkList';
import { addParkItem, deletePark, getImage, getParkDetail, getParktable } from './service';
import type { createParkItem, DetailItem, ParkItem } from './types';
import { typeMapping } from './utils/utils';
const { Option } = Select;
export default () => {
  const [sorter, setSorter] = useState<string>('');
  const [parkDetailVisible, setParkDetailVisible] = useState<boolean>(false);
  const [addListVisible, setAddListVisible] = useState<boolean>(false);
  const [updateListVisible, setUpdateListVisible] = useState<boolean>(false);
  const [configImageVisible, setConfigImageVisible] = useState<boolean>(false);
  const [imgUrls, setImgUrls] = useState<string[]>([]);
  const [currentId, setCurrentId] = useState<string>('');
  const [currItem, setCurrItem] = useState<DetailItem | null>(null);
  const [imgDetail, setImgDetail] = useState<any>([]);
  const actionRef = useRef<ActionType>();
  const createParkingLot = async (fields: createParkItem) => {
    const hide = message.loading('正在提交');
    try {
      const res = await addParkItem(fields);
      hide();
      if (res.code === SUCCESS_CODE) {
        message.success('添加成功');
        setAddListVisible(false);
        actionRef.current?.reload();
        return true;
      }
      message.error(`添加失败！${res.message}`);
      return false;
    } catch (error) {
      hide();
      message.error('添加失败！未知的错误！');
      return false;
    }
  };
  const handleRemove = async (fields: { id: string }) => {
    const hide = message.loading('正在删除');
    try {
      await deletePark(fields);
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };
  const columns: ProColumns<ParkItem>[] = [
    {
      title: '停车场名称',
      dataIndex: 'name',
      ellipsis: true,
      onFilter: true,
    },
    {
      title: '行政区',
      dataIndex: 'city_code',
      onFilter: true,
      search: false,
      // ellipsis: true,
      render: (_, record) => {
        const district = citycode[record.city_code];
        if (String(record.city_code).endsWith('0000')) {
          return <div>{district}</div>;
        } else if (
          !String(record.city_code).endsWith('0000') &&
          String(record.city_code).endsWith('00')
        ) {
          const province = citycode[parseInt(String(record.city_code / 10000)) * 10000];
          return (
            <div>
              {province} {district}
            </div>
          );
        } else if (
          !String(record.city_code).endsWith('0000') &&
          !String(record.city_code).endsWith('00')
        ) {
          const province = citycode[parseInt(String(record.city_code / 10000)) * 10000];
          const city = citycode[parseInt(String(record.city_code / 100)) * 100];
          return (
            <div>
              {province} {city} {district}
            </div>
          );
        }
        return <div>无数据</div>;
      },
    },
    {
      title: '详细地址',
      dataIndex: 'address',
      ellipsis: true,
      search: false,
    },
    {
      title: '计费规则',
      dataIndex: 'scheme_comment',
      ellipsis: true,
      search: false,
      render: (_, record) => <div>{record.scheme ? record.scheme.name : ''}</div>,
    },
    {
      title: '停车场类型',
      dataIndex: 'type',
      ellipsis: true,
      // search: false,
      render: (_, record) => {
        return typeMapping.map((item) => {
          if (record.type == item.type) {
            return <Tag color={item.color}>{item.text} </Tag>;
          } else {
            return ' ';
          }
        });
      },
      renderFormItem: () => {
        return (
          <Select>
            {typeMapping
              .filter((item) => item.option)
              .map((item) => (
                <Select.Option key={item.key} value={item.type}>
                  {item.text}
                </Select.Option>
              ))}
          </Select>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'space_full_status',
      ellipsis: true,
      onFilter: true,
      // valueType: 'select',
      search: false,
      valueEnum: {
        3: { text: '车位不足', status: 'Error' },
        2: { text: '车位紧张', status: 'Warning' },
        1: { text: '车位充足', status: 'Success' },
      },
      renderFormItem: () => (
        <Select>
          <Option value={3}>车位不足</Option>
          <Option value={2}>车位紧张</Option>
          <Option value={1}>车位充足</Option>
        </Select>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (
        text,
        record,
        //  _, action
      ) => {
        const onClickRemove = () => {
          const { name, id } = record;
          Modal.confirm({
            title: `确定要删除 ${name} 吗？`,
            content: (
              <>
                <p>删除之后无法撤回，请谨慎操作！</p>
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove({ id });
            },
            centered: true,
            width: 600,
            style: { height: 400 },
          });
        };
        // const content = (

        // )
        return (
          <>
            <a
              onClick={async () => {
                setUpdateListVisible(true);
                const curr = await getParkDetail(record.id);
                setCurrItem(curr.data);
              }}
            >
              修改
            </a>
            <a style={{ width: 7 }}> </a>
            <a
              style={{ marginLeft: '3px' }}
              onClick={() => {
                setCurrentId(record.id);
                setParkDetailVisible(true);
              }}
            >
              详情
            </a>
            <a style={{ width: 7 }}> </a>
            <Popover
              content={() => {
                return (
                  <>
                    <a
                      onClick={async () => {
                        const res = await getImage(record.id);
                        let uids = -1;
                        setCurrentId(record.id);
                        setImgUrls(res.data);
                        setImgDetail(
                          res.data.map((item: string) => {
                            uids -= 1;
                            return { url: item, status: 'removed', uid: `${uids - 1}` };
                          }),
                        );
                        setConfigImageVisible(true);
                      }}
                    >
                      配置
                    </a>
                    <a style={{ marginLeft: '8px' }} onClick={onClickRemove}>
                      删除
                    </a>
                  </>
                );
              }}
              trigger="click"
            >
              <a style={{ marginLeft: '3px' }}>拓展</a>
            </Popover>
          </>
        );
      },
    },
  ];
  return (
    <PageHeaderWrapper title="停车场列表">
      <ProTable<ParkItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        editable={{
          type: 'multiple',
        }}
        params={{
          sorter,
        }}
        request={(params) => getParktable(params)}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
        }}
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
        }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<ParkItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        dateFormatter="string"
        headerTitle="停车场列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setAddListVisible(true);
            }}
          >
            添加
          </Button>,
        ]}
      />
      {addListVisible && (
        <AddParkList
          visible={addListVisible}
          unVisible={() => {
            setAddListVisible(false);
          }}
          onSubmit={createParkingLot}
        />
      )}
      {currItem && updateListVisible && (
        <UndataParkList
          visible={updateListVisible}
          parkItemData={currItem}
          unVisible={() => {
            setUpdateListVisible(false);
            setCurrItem('');
          }}
          reloadFunc={() => actionRef.current?.reload()}
        />
      )}
      {parkDetailVisible && (
        <ParkDetail
          visible={parkDetailVisible}
          onClose={() => {
            setParkDetailVisible(false);
          }}
          id={currentId}
        />
      )}
      {configImageVisible && (
        <ConfigImage
          Urls={imgUrls}
          visible={configImageVisible}
          unVisible={() => {
            setConfigImageVisible(false);
          }}
          id={currentId}
          reloadFunc={() => actionRef.current?.reload()}
          Image={imgDetail}
        />
      )}
    </PageHeaderWrapper>
  );
};
